import axios from 'axios'

const API_BASE_URL = 'http://localhost:3000/api'

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器
api.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 用户相关API
export const userAPI = {
  login: (username, password) => 
    api.get('/users', { 
      params: { username, password }
    }),
  
  getUsers: () => 
    api.get('/users'),
  
  getUserById: (id) => 
    api.get(`/users/${id}`)
}

// 商品相关API
export const productAPI = {
  getProducts: () => 
    api.get('/products'),
  
  getProductById: (id) => 
    api.get(`/products/${id}`),
  
  createProduct: (product) => 
    api.post('/products', product),
  
  updateProduct: (id, product) => 
    api.patch(`/products/${id}`, product),
  
  deleteProduct: (id) => 
    api.delete(`/products/${id}`)
}

// 购物车相关API
export const cartAPI = {
  getCart: () => 
    api.get('/cart'),
  
  addToCart: (item) => 
    api.post('/cart', item),
  
  updateCartItem: (id, item) => 
    api.patch(`/cart/${id}`, item),
  
  removeFromCart: (id) => 
    api.delete(`/cart/${id}`),
  
  clearCart: () => 
    api.delete('/cart')
}

// 订单相关API
export const orderAPI = {
  getOrders: () => 
    api.get('/orders'),
  
  createOrder: (order) => 
    api.post('/orders', order),
  
  getOrderById: (id) => 
    api.get(`/orders/${id}`),
  
  updateOrderStatus: (id, status) => 
    api.patch(`/orders/${id}`, { status })
}

export default api